package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionQueryObject;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class RegionServiceImpl implements IRegionService{
    @Autowired
    private RegionRepository regionRepository;
    @Autowired
    private MongoTemplate template;
    @Override
    public List<Region> list() {

        return regionRepository.findAll();
    }

    @Override
    public Page<Region> query(RegionQueryObject qo) {
        //条件
        Query query = new Query();
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "_id");
        return DBHelper.query(template,Region.class,query,pageable);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if(!StringUtils.hasLength(region.getId())){
            region.setId(null);
            regionRepository.save(region);
        }else {
            //注意: MongoDB的更新是全量更新,所以操作是先查 再替换 再更新
            //但此时无需注意其他数据,因为刚好页面传过来的参数是与数据库中列的个数是一样的,
            //当后续还有其他情况时则再看,
            regionRepository.save(region);
        }
    }

    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void changeHotValue(String id, int hot) {
        //通过id查询到当前region对象
        Region region = this.get(id);
        //再进行修改操作
        region.setIshot(hot);
        this.update(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public Region get(String rid) {
        /*Optional<Region> optional = regionRepository.findById(rid);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;*/
        return regionRepository.findById(rid).orElse(null);
    }

    @Override
    public List<Region> queryHotRegion() {
        //1.必须热门

        //2.排序 sequence 排序
        return regionRepository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);
    }


}
